from datetime import date
import datetime
import json
from typing import Any
from sqlalchemy.orm import Mapped,Session,mapped_column,DeclarativeBase, relationship,sessionmaker
from app.core.modal import Modal
from sqlalchemy import DateTime,Integer

class BaseModal(Modal):
    __abstract__ = True
    _idGeneratorType='snowflake'    #snowflake 雪花算法 db 用数据库自身自增id
    _soft_delete = False 
    id:Mapped[int]=mapped_column(primary_key=True)
    createdAt:Mapped[date]=mapped_column(DateTime,name="created_at")
    updatedAt:Mapped[date]=mapped_column(DateTime,name="updated_at")
    deletedAt:Mapped[date]=mapped_column(DateTime,name="deleted_at")
    deletedBy:Mapped[int]=mapped_column(Integer,name="deleted_by")
    
    def _datetimeFormat(self,value:datetime.datetime):
        return value.strftime("%Y-%m-%d %H:%M:%S")
    
    def _dateFormat(self,value:datetime.datetime):
        return value.strftime("%Y-%m-%d")
        
    def getCreatedAtAttr(self,value):
        return self._datetimeFormat(value)
    
    def getUpdatedAtAttr(self,value):
        return self._datetimeFormat(value)
    
    def getDeletedAtAttr(self,value):
        return self._datetimeFormat(value)

    def save(self):
        self.updatedAt=datetime.datetime.now()
        if self.id==None:
            self.createdAt=datetime.datetime.now()
        return super().save()

    def delete(self):
        self.deletedAt=datetime.datetime.now()
        if self._soft_delete:
            self.save()
        else:
            return super().delete()
    
    @classmethod
    def query(cls):
        if(cls._soft_delete):
            return super().query().where(cls.deletedAt==None)
        return super().query()
    
    